Cells with odd values in matrix

Time: O(N+M); Space: O(N+M); easy

Given n and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices[i] = [ri, ci]. For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1.

Return the number of cells with odd values in the matrix after applying the increment to all indices.

Example 1:

Input: n = 2, m = 3, indices = [[0,1],[1,1]]

Output: 6

Explanation:

  • Initial matrix = [[0,0,0],[0,0,0]].

  • After applying first increment it becomes [[1,2,1],[0,1,0]].

  • The final matrix will be [[1,3,1],[1,3,1]] which contains 6 odd numbers.

Example 2:

Input: n = 2, m = 2, indices = [[1,1],[0,0]]

Output: 0

Explanation:

  • Final matrix = [[2,2],[2,2]].

  • There is no odd number in the final matrix.

Notes:

  • 1 <= n <= 50

  • 1 <= m <= 50

  • 1 <= len(indices) <= 100

  • 0 <= indices[i][0] < n

  • 0 <= indices[i][1] < m

Hints:

  1. Simulation: With small constraints, it is possible to apply changes to each row and column and count odd cells after applying it.

  2. You can accumulate the number you should add to each row and column and then you can count the number of odd cells.

[1]:
class Solution1(object):
    """
    Time:  O(n + m)
    Space: O(n + m)
    """
    def oddCells(self, n, m, indices):
        """
        :type n: int
        :type m: int
        :type indices: List[List[int]]
        :rtype: int
        """
        row, col = [0]*n, [0]*m
        for r, c in indices:
            row[r] ^= 1
            col[c] ^= 1
        row_sum, col_sum = sum(row), sum(col)
        return row_sum*m + col_sum*n - 2*row_sum*col_sum
[2]:
s = Solution1()
n = 2
m = 3
indices = [[0,1], [1,1]]
assert s.oddCells(n, m, indices) == 6

n = 2
m = 2
indices = [[1,1], [0,0]]
assert s.oddCells(n, m, indices) == 0
[9]:
import collections

class Solution2(object):
    """
    Time:  O(n + m)
    Space: O(n + m)
    """
    def oddCells(self, n, m, indices):
        """
        :type n: int
        :type m: int
        :type indices: List[List[int]]
        :rtype: int
        """
        fn = lambda x: sum(count&1 for count in collections.Counter(x).values())
        row_sum, col_sum = map(fn, zip(*indices))
        return row_sum*m + col_sum*n - 2*row_sum*col_sum
[10]:
s = Solution2()
n = 2
m = 3
indices = [[0,1], [1,1]]
assert s.oddCells(n, m, indices) == 6

n = 2
m = 2
indices = [[1,1], [0,0]]
assert s.oddCells(n, m, indices) == 0